/**
 * 常用方法封装 请求，文件上传等
 **/

const util = {
	ver:'1.1.0',
	test:'',
	fwDate:[],
	//接口地址
	interfaceUrl: function() {
		let domain="https://a.wwdte.com/";
		let sf=wx.getStorageSync('sf') || '';
		if(sf=='worker'){
			return domain+'/api/deerhome.worker.';
		}
		return domain+'/api/deerhome.user.';
	},
	bannerAc(s){
		if(s.type=="no"){
			return;
		}
		if(s.type=="page"){
			wx.navigateTo({
				url:s.page
			})
			return;
		}
		if(s.type=="item"){
			wx.navigateTo({
				url:"/pages/productDetail/productDetail?id="+s.id
			})
			return;
		}
		if(s.type=="yhq"){
			wx.navigateTo({
				url:"/pages/coupon/coupon"
			})
			return;
		}
	},
	/**
	 * promise形式    requestPayment  微信支付
	 * @param pay   后台传递参数,解构
	 * @returns {Promise<unknown>}
	 */
	requestPayment: async function(pay) {
	    return new Promise((resolve, reject) => {
	        wx.requestPayment({
	            ...pay,
	            success(res) {
	                resolve(resolve)
	            },
	            fail(err) {
	                reject(err)
	            }
	        })
	    })
	},

	/**
	 * 定义延时函数
	 * delaytime 延时时长，单位毫秒
	 */
	sleep: async function(delaytime = 1000){
	  return new Promise(resolve => setTimeout(resolve, delaytime));
	},
	toast: function(text, duration, success) {
		wx.showToast({
			title: text || "出错啦~",
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},
	ask:function(str,callback){
		wx.showActionSheet({
			title:str,
			itemList: ['确定'],
			success: function (res) {
				callback && callback();
			},
			fail: function (res) {
				console.log(res.errMsg);
			}
		});
	},
	confirm: async function(title,desc){
		return new Promise((resolve, reject) => {
				wx.showModal({
					title: title,
					content:desc || '',
					confirmColor:'#e41f19',
					success: function (res) {
						if (res.confirm) {
							resolve();
						} else if (res.cancel) {
							reject();
						}
					}
				});
			}
		);
	},
	saveToPhoto:function(callback){
		wx.authorize({
			/* scope.writePhotosAlbum 类型是保存到相册 */
			scope: 'scope.writePhotosAlbum',
			success() {
				callback && callback();
			},
			complete(res) {
				/* 判断如果没有授权就打开设置选项让用户重新授权 */
				wx.getSetting({
					success(res) {
						if (!res.authSetting['scope.writePhotosAlbum']) {
						   /* 打开设置的方法 */
							util.openInstall(callback);
						}
					}
				});
			}
		});
	},
	openInstall:function(callback) {
		wx.showModal({
			content: '没有授权保存图片到相册,点击确定去允许授权',
			success: function(res) {
				if (res.confirm) {
					/* 打开设置的API*/
					wx.openSetting({
						success(res) {
							console.log(res.authSetting);
						}
					});
				} else if (res.cancel) {
					wx.showModal({
						cancelText: '取消',
						confirmText: '重新授权',
						content: '你点击了取消，将无法进行保存操作',
						success: function(res) {
							if (res.confirm) {
								wx.openSetting({
									success(res) {
										callback && callback();
									}
								});
							} else if (res.cancel) {
								util.toast('没有授权，无法保存')
							}
						}
					});
				}
			}
		});
	},
	alert(str,tip,callback){
		wx.showModal({
			title: str,
			content: tip || '',
			showCancel: false,
			confirmColor: "#4fc789",
			confirmText: "我知道了",
			success(res) {
				if (res.confirm) {
					callback && callback()
				}
			}
		})
	},
	modal: function(title, content, showCancel, callback, confirmColor, confirmText,cancelText) {
		wx.showModal({
			title: title || '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: "#555",
			cancelText:cancelText || '取消',
			confirmColor: confirmColor || "#EB0909",
			confirmText: confirmText || "确定",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	isAndroid: function() {
		const res = wx.getSystemInfoSync();
		return res.platform.toLocaleLowerCase() == "android"
	},
	isPhoneX: function() {
		const res = wx.getSystemInfoSync();
		return res.safeAreaInsets.bottom > 0;
	},
	constNum: function() {
		let time = 0;
		// #ifdef APP-PLUS
		time = this.isAndroid() ? 300 : 0;
		// #endif
		return time
	},
	delayed: null,
	showLoading: function(title, mask = true) {
		wx.showLoading({
			mask: mask,
			title: title || '请稍候...'
		})
	},
	wxLoginSys:async function(){
		return new Promise((reslove) => {
		    wx.login({
		      success(res) {
		        reslove(res.code);
		      }
		    })
		})
	},
	getOpenIdSys:async function(par){
		let pagePar = par || {};
		console.log('getOpenIdSys',pagePar);
		if(wx.getStorageSync("openid")){
			return {};
		}
		let newPar={};
		if(pagePar.scene){
			let scene=decodeURIComponent(pagePar.scene);
			scene=scene.split("&");
			for(let i=0;i<scene.length;i++){
				let a=scene[i].split("=");
				if(a.length==2){
					newPar[a[0]]=a[1];
				}
			}
		}else{
			newPar=pagePar;
		}
		console.log('newPar',newPar);
		console.log('get token start');
		let code=await util.wxLoginSys();
		newPar.code=code;
		let res= await util.post('login/wxbd',newPar,false);
		wx.setStorageSync("openid", res.data.openid);
		console.log('get token end');
		return res;
	},
	
	post: async function(url,  postData={}, hideLoading=true,isDelay=false) {
		return util.request(url,'post',postData, isDelay, false, hideLoading);
	},
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param string method 请求方式
	 *  GET or POST
	 * @param {*} postData 请求参数
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool isForm 数据格式
	 *  true: 'application/x-www-form-urlencoded'
	 *  false:'application/json'
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	request: async function(url, method, postData, isDelay, isForm, hideLoading) {
		//接口请求
		let loadding = false;
		util.delayed && wx.hideLoading();
		clearTimeout(util.delayed);
		util.delayed = null;
		if (!hideLoading) {
			if (isDelay) {
				util.delayed = setTimeout(() => {
					loadding = true
					util.showLoading()
				}, 1000)
			} else {
				loadding = true
				util.showLoading()
			}
		}
		return new Promise((resolve, reject) => {
			wx.request({
				url: util.interfaceUrl() + url,
				data: postData,
				header: {
					'Content-Type': isForm ? 'application/x-www-form-urlencoded' : 'application/json',
					'Deer-Device-Type':'wxapp',
					'Deer-Api-Version':util.ver,
					'Deer-Api-Token': util.getToken(),
					'Deer-Api-Openid': wx.getStorageSync('openid')
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					clearTimeout(util.delayed)
					util.delayed = null;
					if (loadding && !hideLoading) {
						wx.hideLoading()
					}
					if(res.data.code==0){
						resolve(res.data);
						return;
					}
					if(res.data.code==100){
						wx.removeStorageSync("is_login");
						wx.removeStorageSync("user_token");
						util.toast(res.data.msg);
						reject(res.data)
						return;
					}
					if(res.data.alert==1){
						util.alert(res.data.msg);
					}else{
						util.toast(res.data.msg);
					}
					reject(res.data)
				},
				fail: (res) => {
					clearTimeout(util.delayed)
					util.delayed = null;
					util.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	},
	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadFile: function(url, src, hideLoading=false,formData={}) {
		hideLoading && util.showLoading();
		return new Promise((resolve, reject) => {
			const uploadTask = wx.uploadFile({
				url: util.interfaceUrl() + url,
				filePath: src,
				name: 'file',
				header: {
					'Deer-Device-Type':'wxapp',
					'Deer-Api-Version':util.ver,
					'Deer-Api-Token': util.getToken()
				},
				formData: formData,
				success: function(res) {
					console.log('upload:',res)
					hideLoading &&  wx.hideLoading()
					let d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
					if (d.code % 100 == 0) {
						//返回图片地址
						let fileObj = d.data;
						resolve(fileObj)
					} else {
						util.toast(res.msg);
						reject(res.msg);
					}
				},
				fail: function(res) {
					hideLoading &&  wx.hideLoading()
					reject(res)
					util.toast('err:'+res.msg);
				}
			})
		})
	},
	tuiJsonp: function(url, callback, callbackname) {
		// #ifdef H5
		window[callbackname] = callback;
		let tuiScript = document.createElement("script");
		tuiScript.src = url;
		tuiScript.type = "text/javascript";
		document.head.appendChild(tuiScript);
		document.head.removeChild(tuiScript);
		// #endif
	},
	//设置用户信息
	setUserInfo: function(mobile, token) {
		//wx.setStorageSync("thorui_token", token)
		wx.setStorageSync("thorui_mobile", mobile)
	},
	setToken(token) {
		return wx.setStorageSync("user_token",token);
	},
	//获取token
	getToken() {
		let sf=wx.getStorageSync('sf') || '';
		if(sf=='worker'){
			return wx.getStorageSync("worker_token");
		}
		return wx.getStorageSync("user_token");
	},
	//设置token
	setWxToken(token) {
		return wx.setStorageSync("wx_token",token);
	},
	getWxToken() {
		return wx.getStorageSync("wx_token");
	},
	//判断是否登录
	isLogin: function() {
		// return true;
		return wx.getStorageSync("is_login")==1 ? true : false
	},
	//判断登录并跳转
	checkLogin:async function(){
		return new Promise((resolve, reject) => {
			if(util.isLogin()){
				resolve();
				return;
			}
			wx.navigateTo({
				url: '/pages/login/login'
			})
			reject();
		})
	},
	//跳转页面，校验登录状态
	href(url, isVerify) {
		if (isVerify && !util.isLogin()) {
			wx.navigateTo({
				url: '/pages/login/login'
			})
		} else {
			wx.navigateTo({
				url: url
			});
		}
	},
	//版本更新
	//版本升级提示
	upgradeTip(){
		if (!wx.canIUse('getUpdateManager')) {
			wx.showModal({
				title: '提示',
				content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
			})
			return;
		}
		const updateManager = wx.getUpdateManager();
		// 监听向微信后台请求检查更新结果事件
		updateManager.onCheckForUpdate(function (res) {
			//如果hasUpdate为true表示有版本更新
			if (!res.hasUpdate) {
				return;
			}
			//小程序有版本更新事件回调
			updateManager.onUpdateReady(function () {
				wx.showModal({
				  title: '更新提示',
				  content: '新版本已经准备好，是否重启小程序？',
				  showCancel:false,
				  success: function (res) {
					if (res.confirm) {
					  //强制小程序重启并使用新版本
					  updateManager.applyUpdate();
					}
				  }
				})
			});
			//监听小程序更新失败事件
			updateManager.onUpdateFailed(function () {
				wx.showModal({
				  title: '已经有新版本了哟~',
				  content: '新版本已经上线啦~，请关掉微信APP，重新进入',
				  showCancel:false,
				  confirmText:'我知道了'
				})
			});
		})
	},
	//去空格
	trim: function(value) {
		return value.replace(/(^\s*)|(\s*$)/g, "");
	},
	//内容替换
	replaceAll: function(text, repstr, newstr) {
		return text.replace(new RegExp(repstr, "gm"), newstr);
	},
	//格式化手机号码
	formatNumber: function(num) {
		return num.length === 11 ? num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') : num;
	},
	//获取当前的地理位置
	getLocation:async function() {
		return new Promise((resolve, reject) => {
			wx.getLocation({
				type: 'gcj02',
				isHighAccuracy: false,
				geocode: false,
				highAccuracyExpireTime: 3500,
				success: (res) => {
					resolve(res);
				},
				fail: (res) => {
					if (res.errMsg == "getLocation:fail auth deny") {
						wx.showModal({
							content: '检测到您没打开获取信息功能权限，是否去设置打开？',
							confirmText: "确认",
							cancelText: '取消',
							success: (res) => {
								if (res.confirm) {
									wx.openSetting({
										success: (res) => {}
									})
								} else {
									return false;
								}
							}
						})
						return;
					}
					reject();
				}
			})
		})
	}
}

export default util;
